module vfs.document;

import utils.log;

import std.stream;
import core.thread;
import vfs.documenttype;
import vfs.documentmanager;
import lang.isyntaxelement;
import lang.languagefactory;
import lang.language;

class Document {
    private string myContent;
    private DocumentType myType;
    private shared(ISyntaxElement) mySyntaxElement;

    public this(in string path) {
        myType = DocumentManager.getTypeFromPath(path);
        scope File file = new File(path);
        while (!file.eof()) {
            myContent ~= file.readLine();
        }
        file.close();
        (new Thread(&analizeContent)).start();
    }

    private void analizeContent() {
        shared(Language) lang = LanguageFactory.getLanguage(myType);
        if (lang is null) {
            mySyntaxElement = null;
            return;
        }
        synchronized {
            mySyntaxElement = lang.analize(myContent);
        }
    }

    public DocumentType getType() const {
        return myType;
    }

    /// How update that part of document, which was changed???
    /// TODO: Do something with it!!! It is very terrible
    public void updateDocument(in string newContent) {
        myContent = newContent;
        (new Thread(&analizeContent)).start();
    }
}

version(unittest) {
    import std.file;

    unittest {
        OutputStream stream = new File("testdocument.d", FileMode.OutNew);
        stream.writeLine("module testdocument; import std.stdio;");
        stream.close();
        scope(exit) {
            remove("testdocument.d");
        }
        Document doc = new Document("testdocument.d");
        uint i = 0;
        Thread.getThis().sleep(10_000);
        assert(doc.mySyntaxElement !is null);
    }
}
